//
//  CYUtils.m
//  T-BoxManager
//
//  Created by 车音 on 2019/6/24.
//  Copyright © 2019 CheYin. All rights reserved.
//

#import "CYUtils.h"
#import <CommonCrypto/CommonCrypto.h>
#import "sys/utsname.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>


#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"


@implementation CYUtils

+ (BOOL)isNullOrNil:(id)data {
    return (!data) || [data isEqual:[NSNull null]];
}

+ (BOOL)isEmptyString:(NSString *)string {
    return string == nil
    || [string isEqual:[NSNull null]]
    || ![string isKindOfClass:[NSString class]]
    || string.length == 0;
}


/**
 获取非空字符串
 */
+ (NSString *)getExistString:(NSString *)text{
    if ([self isEmptyString:text]) {
        return @"";
    }else{
        return text;
    }
}


+ (BOOL)isEqualsString:(NSString *)str1 to:(NSString *)str2 {
    if([self isEmptyString:str1] && [self isEmptyString:str2]) {
        return YES;
    } else {
        if(![self isEmptyString:str1]) {
            return [str1 isEqualToString:str2];
        } else {
            return [str2 isEqualToString:str1];
        }
    }
}

+ (void)log:(NSString *)format, ... {
    va_list args;
    va_start(args, format);
    NSString *str = [[NSString alloc]initWithFormat:format arguments:args];
    va_end(args);
    printf("%s\n",[str UTF8String]);
}

+ (id)string2object:(NSString *)src {
    NSData *JSONData = [src dataUsingEncoding:NSUTF8StringEncoding];
    return [self data2object:JSONData];
}

+ (id)data2object:(NSData *)data {
    if (!data) {
        return nil;
    }
    return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
}

+ (BOOL)hasChinese:(NSString *)str {
    if(![str isKindOfClass:[NSString class]]){
        return NO;
    }
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}

+ (BOOL)isJPEGValid:(NSData *)jpeg {
    if ([jpeg length] < 4) return NO;
    const unsigned char * bytes = (const unsigned char *)[jpeg bytes];
    if (bytes[0] != 0xFF || bytes[1] != 0xD8) return NO;
    if (bytes[[jpeg length] - 2] != 0xFF || bytes[[jpeg length] - 1] != 0xD9) return NO;
    return YES;
}

+ (NSString *)randomString:(NSInteger)count {
    if(count <= 0) {
        return @"";
    }
    if(count > 100) {
        count = 100;
    }
    char data[count];
    for (int x = 0; x < count; data[x++] = (char)('A' + (arc4random_uniform(26))));
    return [[NSString alloc] initWithBytes:data length:count encoding:NSUTF8StringEncoding];
}

/**
 获取随机数
 @param count 随机数长度
 @return 随机数
 */
+ (NSString *)random:(NSInteger)count {
    NSString *strRandom = @"";
    for(int i = 0; i < count; i++) {
        strRandom = [strRandom stringByAppendingFormat:@"%i",(arc4random() % 9)];
    }
    return strRandom;
}

+(NSString*)stringToMD5:(NSString *)str{
    //要进行UTF8的转码
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02X", result[i]];
    }
    return digest;
}


+(NSString*)stringToSHA1:(NSString *)str{
    //这两句容易造成 、中文字符串转data时会造成数据丢失
    //const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    //NSData *data = [NSData dataWithBytes:cstr length:input.length];
    //instead of
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}


+ (NSString *)urlEncode:(NSString *)urlString {
    if (!urlString) {
        return nil;
    }
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                                    (CFStringRef)urlString,
                                                                                                    NULL,
                                                                                                    (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                                    kCFStringEncodingUTF8));
    return encodedString;
}

+ (NSString *)timestamp {
    return [NSString stringWithFormat:@"%d", (int)[[NSDate date] timeIntervalSince1970]];
}

+ (NSString *)timestampMillisecond {
    return [NSString stringWithFormat:@"%ld", (long)([[NSDate date] timeIntervalSince1970]*1000)];
}


+ (NSString *)urlDecode:(NSString *)urlString {
    if (!urlString) {
        return nil;
    }
    NSMutableString *outputStr = [NSMutableString stringWithString:urlString];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

+ (NSString *)systemName {
    return [UIDevice currentDevice].name;
}

+ (NSString *)systemVersion {
    return [UIDevice currentDevice].systemVersion;
}

+ (NSString *)systemString {
    UIDevice *device = [UIDevice currentDevice];
    return [NSString stringWithFormat:@"%@ %@", device.systemName, device.systemVersion];
}

+ (NSString *)appBundleId {
    return [[NSBundle mainBundle] bundleIdentifier];
}

+ (NSString *)appName {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
}

+ (NSString *)appVersion {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

+ (NSString *)appBuildCode {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}

+ (CGFloat)statusBarHeight {
    CGRect statusRect = [[UIApplication sharedApplication] statusBarFrame];
    return statusRect.size.height;
}

+ (BOOL)isFirstBoot {
    NSString *localVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"CYappVersion"];
    BOOL isFirst = ![localVersion isEqualToString:[CYUtils appVersion]];
    [[NSUserDefaults standardUserDefaults] setValue:[CYUtils appVersion] forKey:@"CYappVersion"];
    return isFirst;
}



+ (BOOL)effectiveNumber:(NSString *)mobile {
    if (mobile.length < 11)
    {
        return NO;
    } else {
//        /**
//         * 移动号段正则表达式
//         */
//        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
//        /**
//         * 联通号段正则表达式
//         */
//        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(175)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
//        /**
//         * 电信号段正则表达式
//         */
        NSString *CT_MOBILE = @"^(1)\\d{10}$";
//        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
//        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
//        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
//        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_MOBILE];
        BOOL isMatch = [pred evaluateWithObject:mobile];
        
        if (isMatch) {
            return YES;
        } else {
            return NO;
        }
    }
    return NO;
}


/**
 是否是正确邮箱号码
 */
+ (BOOL)isCorrectEmail:(NSString *)EmailStr{
    NSString *emailRegex = @"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:EmailStr];
}


+ (NSString *)currentDateStr {
    return [CYUtils currentDateStr:@"yyyy-MM-dd HH:mm:ss"];
}

+ (NSString *)formatDate:(NSDate *)date format:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:date];
}

+ (id)strigASCIIEncoding:(NSString *)string {
    id data = [string dataUsingEncoding:NSASCIIStringEncoding];
    return [self objectData:data];
}

+ (id)objectData:(NSData *)data {
    if (!data) {
        return nil;
    }
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                    options:NSJSONReadingAllowFragments
                                                      error:nil];
    return jsonObject;
}

+ (NSString *)currentDateStr:(NSString *)format {
    return [CYUtils formatDate:[NSDate date] format:format];
}



+ (NSString*)object2string:(id)object {
    if(!object) {
        return nil;
    }
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}


+ (NSDate *)dateFromString:(NSString *)yyyy_MM_dd {
    return [CYUtils dateFromString:yyyy_MM_dd format:@"yyyy-MM-dd"];
}

+ (NSDate *)dateFromString2:(NSString *)yyyy_MM_ddTHH_mm_ss {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
    
    if (![yyyy_MM_ddTHH_mm_ss containsString:@"+"]) {
        yyyy_MM_ddTHH_mm_ss = [NSString stringWithFormat:@"%@+08:00", yyyy_MM_ddTHH_mm_ss];
    }
    
    return [dateFormatter dateFromString:yyyy_MM_ddTHH_mm_ss];
}
+ (NSDate *)dateFromString3:(NSString *)yyyy_MM_ddTHH_mm_ss_SSSZ {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
    
    return [dateFormatter dateFromString:yyyy_MM_ddTHH_mm_ss_SSSZ];
}

+ (NSDate *)dateFromString4:(NSString *)yyyy_MM_ddTHH_mm_ssZ {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    
    return [dateFormatter dateFromString:yyyy_MM_ddTHH_mm_ssZ];
}

+ (NSDate *)dateFromString5:(NSString *)yyyy_MM_dd_HH_mm_ss {
    return [CYUtils dateFromString:yyyy_MM_dd_HH_mm_ss format:@"yyyy-MM-dd HH:mm:ss"];
}

+ (NSDate *)dateFromString:(NSString *)dateString format:(NSString *)format {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = format;
    return [fmt dateFromString:dateString];
}

+ (NSString *)timeFromSecond:(double)second {
    NSInteger h = second/(60*60);
    NSInteger remainTimeInterger = abs(((int)second)%(60*60));
    NSInteger m = remainTimeInterger/60;
    NSInteger s = remainTimeInterger%60;
    
    NSString *hStr = @"";
    NSString *mStr = @"";
    NSString *sStr = @"";
    
    if (h < 10) {
        hStr = [NSString stringWithFormat:@"0%ld",(long)h];
    } else {
        hStr = [NSString stringWithFormat:@"%ld",h];
    }
    
    if (m < 10) {
        mStr = [NSString stringWithFormat:@"0%ld",m];
    } else {
        mStr = [NSString stringWithFormat:@"%ld",m];
    }
    
    if (s < 10) {
        sStr = [NSString stringWithFormat:@"0%ld",s];
    } else {
        sStr = [NSString stringWithFormat:@"%ld",s];
    }
    
    NSString *timeStr = [NSString stringWithFormat:@"%@:%@:%@",hStr,mStr,sStr];
    return timeStr;
}

+ (NSString *)timeFromMillsecond2:(long long)millsecond {
    if(time <= 0)
    {
        return @"";
    }
    int targetDay = (int)(millsecond / 86400000l);
    int nowDay = (int) ([[NSDate date] timeIntervalSince1970]/86400);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    if(targetDay == nowDay)
    {
        [formatter setDateFormat:@"HH:mm"];
        return [formatter stringFromDate:[[NSDate alloc] initWithTimeIntervalSince1970:millsecond/1000]];
    }
    else if(targetDay + 1 == nowDay)
    {
        [formatter setDateFormat:@"昨天:HH:mm"];
        return [formatter stringFromDate:[[NSDate alloc] initWithTimeIntervalSince1970:millsecond/1000]];
    }
    else
    {
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        return [formatter stringFromDate:[[NSDate alloc] initWithTimeIntervalSince1970:millsecond/1000]];
    }
}


+ (NSString *)loadActivityStartTimer:(NSString *)creat_time {
    NSDate *nowDate = [NSDate date]; ///< 当前时间
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH-mm-ss";
    NSDate *creat = [formatter dateFromString:creat_time]; ///< 传入的时间
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *compas = [calendar components:unit fromDate:creat toDate:nowDate options:0];
    NSLog(@"year=%zd  month=%zd  day=%zd hour=%zd  minute=%zd",compas.year, compas.month,compas.day, compas.hour, compas.minute);
    
    NSString *startTimer = @"";
    if (compas.year) {
        startTimer = [NSString stringWithFormat:@"%ld:%ld:%ld:%ld:%ld",compas.year, compas.month, compas.day, compas.hour, compas.minute];
    } else if (!compas.year && compas.month) {
        startTimer = [NSString stringWithFormat:@"%ld:%ld:%ld:%ld",compas.month, compas.day, compas.hour, compas.minute];
    } else if (!compas.year && !compas.month && compas.day) {
        startTimer = [NSString stringWithFormat:@"%ld:%ld:%ld", compas.day, compas.hour, compas.minute];
    } else if (!compas.year && !compas.month && !compas.day && compas.hour) {
        startTimer = [NSString stringWithFormat:@"00:%ld:%ld", compas.hour, compas.minute];
    } else if (!compas.year && !compas.month && !compas.day && !compas.hour && compas.minute) {
        startTimer = [NSString stringWithFormat:@"00:00:%ld", compas.minute];
    } else {
        startTimer = [NSString stringWithFormat:@"00:00:00"];
    }
    
    if ([startTimer containsString:@"-"]) {
        startTimer = [startTimer stringByReplacingOccurrencesOfString:@"-" withString:@""];
        return startTimer;
    } else {
        return @"00:00:00";
    }
}


+ (NSString *)getTimeFromTimestamp:(NSString *)timeString formatter:(NSString *)formatterString{
    
    NSTimeInterval interval = [timeString doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatterString];
    
    NSString *dateString = [formatter stringFromDate: date];
    return dateString;
    
}


+ (BOOL)getIsIpad
{
    NSString *deviceType = [UIDevice currentDevice].model;
    if ([deviceType isEqualToString:@"iPhone"]) {
        //iPhone
        return NO;
    }
    else if([deviceType isEqualToString:@"iPod touch"]) {
        //iPod Touch
        return YES;
    }
    else if([deviceType isEqualToString:@"iPad"]) {
        //iPad
        return YES;
    }
    return NO;
}

+ (NSString *)removeLastOneChar:(NSString *)origin {
    NSString *cutted;
    if ([origin length] > 0){
        cutted = [origin substringToIndex:([origin length] - 4)];
    } else {
        cutted = origin;
    }
    return cutted;
}

+ (BOOL)isInstallBaiduMap {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]];
}

+ (BOOL)isInstallIosAMap {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]];
}

+ (BOOL)isInstallComgooglemaps {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]];
}

+ (BOOL)isInstallQQMap {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"qqmap://"]];
}

+ (BOOL)isInstallIphoneMap {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"maps://"]];
}


/**
 跳转系统通知页面
 */
+(void)enterSystemSettingNotity{
    
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    } else {
        NSURL*url=[NSURL URLWithString:@"App-Prefs:root=NOTIFICATIONS_ID"];
        
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            
            [[UIApplication sharedApplication] openURL:url];
        };
    }
}


/**
 跳转手机密码页面
 */
+(void)enterSystemPasscodeSetting{
    
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    } else {
        NSURL*url=[NSURL URLWithString:@"App-Prefs:root=PASSCODE"];
        
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            
            [[UIApplication sharedApplication] openURL:url];
        };
    }
    
}


+ (BOOL)isLengthToEleven:(NSString *)mobile{
    if (mobile.length == 11) {
        return YES;
    }
    return NO;
}


/**
 是否是正确身份证号码
 */
+ (BOOL)isCorrectIDCard:(NSString *)IDCardStr{
    IDCardStr = [IDCardStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([IDCardStr length] != 18) {
        return NO;
    }
    NSString *mmdd = @"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";
    NSString *leapMmdd = @"0229";
    NSString *year = @"(19|20)[0-9]{2}";
    NSString *leapYear = @"(19|20)(0[48]|[2468][048]|[13579][26])";
    NSString *yearMmdd = [NSString stringWithFormat:@"%@%@", year, mmdd];
    NSString *leapyearMmdd = [NSString stringWithFormat:@"%@%@", leapYear, leapMmdd];
    NSString *yyyyMmdd = [NSString stringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd, @"20000229"];
    NSString *area = @"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";
    NSString *regex = [NSString stringWithFormat:@"%@%@%@", area, yyyyMmdd  , @"[0-9]{3}[0-9Xx]"];
    
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![regexTest evaluateWithObject:IDCardStr]) {
        return NO;
    } else {
        return YES;
    }
    
}


/**
 验证密码的难度等级
 */
+ (NSString *)verifyPasswordGradeWithPwd:(NSString *)password{
    
    //符合长度情况下
    //输入的纯数字为弱
    //输入的纯小写字母为弱
    //输入的纯大写字母为弱
    //输入的大写字母和数字，输入的字符小于7个密码为弱
    //输入的大写字母和数字，输入的字符大于等于7个密码为中
    //输入的小写字母和数字，输入的字符小于7个密码为弱
    //输入的小写字母和数字，输入的字符大于等于7个密码为中
    //输入的大写字母和小写字母，输入的字符小于7个密码为弱
    //输入的大写字母和小写字母，输入的字符大于等于7个密码为中
    //输入的大写字母和小写字母和数字，输入的字符小于7个密码为中
    //输入的大写字母和小写字母和数字，输入的字符大于等于7个密码为强
    
    NSString *passwordGrade = @"弱";
    NSString *weakGrade = @"^([A-Z])\\d{6,18}|([a-z])\\d{6,18}|([0-9])\\d{6,18}|(?:(?=.*[A-Z])(?=.*[a-z])).{6,}|(?:(?=.*[A-Z])(?=.*[0-9])).{6,}|(?:(?=.*[a-z])(?=.*[0-9])).{6,}$";
    NSString *middleGrade = @"^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).{6,}|(?:(?=.*[A-Z])(?=.*[a-z])).{7,18}|(?:(?=.*[A-Z])(?=.*[0-9])).{7,18}|(?:(?=.*[a-z])(?=.*[0-9])).{7,18}$";
    NSString *hardGrade = @"^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).{7,18}$";
    
    NSPredicate *weakG = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", weakGrade];
    BOOL isWeak = [weakG evaluateWithObject:password];
   
    NSPredicate *middleG = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", middleGrade];
    BOOL isMiddle = [middleG evaluateWithObject:password];
    
    NSPredicate *hardG = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", hardGrade];
    BOOL isHard = [hardG evaluateWithObject:password];
    
    if (isWeak) {
        passwordGrade = @"弱";
    }
    if (isMiddle) {
        passwordGrade = @"中";
    }
    if (isHard) {
        passwordGrade = @"强";
    }
    return passwordGrade;
}


/**
 获得字体高度方法
 */
+ (CGFloat)getFontHeightUseString:(NSString *)textStr Width:(CGFloat)width FontSize:(CGFloat)fontSize
{
    CGRect rect = [textStr boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:fontSize]} context:nil];
    return ceil(rect.size.height);
}


/**
 获得带行间距字体高度方法
 */
+ (CGFloat)getFontHeightUseString:(NSString *)textStr Width:(CGFloat)width FontSize:(CGFloat)fontSize Distance:(CGFloat)textDistance{
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = textDistance;//调整行间距
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;//保留所有字符,没有...
    
    //NSKernAttributeName:@1.5f 文字间距
    //    NSDictionary *attributeDict = @{NSFontAttributeName : [UIFont systemFontOfSize:fontSize],NSParagraphStyleAttributeName:paragraphStyle, NSKernAttributeName:@1.5f };
    
    NSDictionary *attributeDict = @{NSFontAttributeName : [UIFont systemFontOfSize:fontSize],NSParagraphStyleAttributeName:paragraphStyle};
    
    CGRect rect = [textStr boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading attributes:attributeDict context:nil];
    
    //文本的高度减去字体高度小于等于行间距，判断为当前只有1行
    if ((rect.size.height - [UIFont systemFontOfSize:fontSize].lineHeight) <= paragraphStyle.lineSpacing) {
        if ([self hasChinese:textStr]) {
            //如果包含中文
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing);
        }
    }
    
    return ceil(rect.size.height);
    
}


/**
 获取带行间距的属性字符串
 */
+(NSAttributedString *)getAttributedStringWithString:(NSString *)string lineSpace:(CGFloat)lineSpace withAlignment:(NSTextAlignment)alignment{
    if (string == nil || string.length == 0) {
        string = @"";
    }
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace; // 调整行间距
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;//保留所有字符,没有...
    paragraphStyle.alignment = alignment;
    NSRange range = NSMakeRange(0, [string length]);
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    
    return attributedString;
}

/**
 打电话功能
 @param phoneStr 手机号码
 */
+ (void)callPhoneUseNumber:(NSString *)phoneStr
{
    if ([phoneStr isKindOfClass:[NSString class]] && phoneStr && phoneStr && phoneStr.length > 0) {
        NSString *callPhoneStr = [NSString stringWithFormat:@"telprompt://%@", phoneStr];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhoneStr] options:@{} completionHandler:^(BOOL success) {
            }];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhoneStr]];
        }
    } else {
        CYLog(@"手机号码不存在");
    }
    
}

/**
 获取Window当前显示的ViewController
 */
+ (UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}

/**
 处理开始时间标准化显示
 */
+ (NSString *)getDefaultStartTimeWithHours:(NSString *)hours andMinute:(NSString *)minute{
    
    // 处理时间比对
    if (hours.integerValue < 10) {
        hours = [NSString stringWithFormat:@"0%@",hours];
    }else{
        hours = [NSString stringWithFormat:@"%@",hours];
    }
    if (minute.integerValue < 10) {
        minute = [NSString stringWithFormat:@"0%@",minute];
    }else{
        minute = [NSString stringWithFormat:@"%@",minute];
    }
    
    NSString *startTime = [NSString stringWithFormat:@"%@:%@",hours,minute];
    return startTime;
}


/**
 过滤器/ 将.f格式化的字符串，去除末尾0
 @param numberStr 需要格式化的字符串
 @return 去除末尾0之后的
 */
+ (NSString *)removeSuffix:(NSString *)numberStr{
    if (fmodf(numberStr.floatValue, 1)==0) {//如果有一位小数点
        return [NSString stringWithFormat:@"%.0f",numberStr.floatValue];
    } else if (fmodf(numberStr.floatValue*10, 1)==0) {//如果有两位小数点
        return [NSString stringWithFormat:@"%.1f",numberStr.floatValue];
    } else if (fmodf(numberStr.floatValue*100, 1)==0) {//如果有三位小数点
        return [NSString stringWithFormat:@"%.2f",numberStr.floatValue];
    }else if (fmodf(numberStr.floatValue*1000, 1)==0) {//如果有四位小数点
        return [NSString stringWithFormat:@"%.3f",numberStr.floatValue];
    }else {
        return [NSString stringWithFormat:@"%.4f",numberStr.floatValue];
    }
}


/// 过滤器/ 将.2f格式化的字符串，去除末尾0(不进位)
/// @param numberStr 需要格式化的字符串
+ (NSString *)removeSuffixNOCarry:(NSString *)numberStr{
    if (numberStr.length > 1) {
        numberStr = [NSString stringWithFormat:@"%.2f",floor(([numberStr floatValue])*100)/100];
        if ([numberStr componentsSeparatedByString:@"."].count == 2) {
            NSString *last = [numberStr componentsSeparatedByString:@"."].lastObject;
            if ([last isEqualToString:@"00"]) {
                numberStr = [numberStr substringToIndex:numberStr.length - (last.length + 1)];
                return numberStr;
            }else{
                if ([[last substringFromIndex:last.length -1] isEqualToString:@"0"]) {
                    numberStr = [numberStr substringToIndex:numberStr.length - 1];
                    return numberStr;
                }
            }
        }
        return numberStr;
    }else{
        return @"";
    }
}


/**
 对字符串进行保留两位,后面的舍去(不四舍五入,不丢失经度),如果是0也要舍去
 */
+ (NSString *)removeSuffixWithString:(NSString *)string{
    NSString *finalStr = @"";
    if ([string containsString:@"."]) {
        NSArray *strArr = [string componentsSeparatedByString:@"."];
        if (strArr.count>1) {
            NSString *tempStr = strArr.lastObject;//小数点后面的字符串
            if (tempStr.length>2) {
                tempStr = [tempStr substringWithRange:NSMakeRange(0, 2)];
            }
            if ([tempStr isEqualToString:@"00"]) {
                tempStr = @"";
                return strArr.firstObject;
            }else{
                if ([[tempStr substringFromIndex:tempStr.length -1] isEqualToString:@"0"]) {
                    tempStr = [tempStr substringToIndex:tempStr.length - 1];
                }
            }
            finalStr = [NSString stringWithFormat:@"%@.%@",strArr.firstObject,tempStr];
        }else{
            return string;
        }
    }else{
        finalStr = string;
    }
    return finalStr;
}

+ (NSString *)floatStr:(NSString *)string{
    return [NSString stringWithFormat:@"%.2f",[string floatValue]];
}

//电量处理
+ (NSString *)handleElectricity:(NSString *)string{
    if ([string containsString:@"."]) {
        NSArray *strArr = [string componentsSeparatedByString:@"."];
        NSString *tempStr = strArr.lastObject;
        if (tempStr.length > 2) {
            //大于2 取后两位
            return [CYUtils floatStr:string];
        }
    }
    return string;
}

/**
 计算时间差值
 @param starTime 开始时间
 @param endTime 结束时间
 @return 差值 秒
 */
+ (NSInteger)differenceInsertStarTime:(NSString *)starTime andInsertEndTime:(NSString *)endTime{
    NSDateFormatter* formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//根据自己的需求定义格式
    NSDate* startDate = [formater dateFromString:starTime];
    NSDate* endDate = [formater dateFromString:endTime];
    NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
    return (int)time;
}


/**
 通过功能名称+vin生成一个存储时间的key值
 @param actionName 控车功能名称
 @return key值
 */
+(NSString *)getControlTimeKeyWithActionName:(NSString *)actionName vinStr:(NSString *)vinStr{
    return [actionName stringByAppendingString:vinStr];
}

/**
 取html字符串中的img
 */
+ (NSArray *)filterImageWithHtml:(NSString *)html{
    
    if (isEmptyString(html)) {
        return [NSArray array];
    }
    NSMutableArray *resultArray = [NSMutableArray array];
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|IMG)(.*?)(/>|>|>)" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    
    NSArray *result = [regex matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(0, html.length)];
    
    for (NSTextCheckingResult *item in result) {
        
        NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:0]];
        
        NSArray *tmpArray = nil;
        
        if ([imgHtml rangeOfString:@"src=\""].location != NSNotFound) {
            
            tmpArray = [imgHtml componentsSeparatedByString:@"src=\""];
            
        } else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
            
            tmpArray = [imgHtml componentsSeparatedByString:@"src="];
            
        }
        
        if (tmpArray.count >= 2) {
            
            NSString *src = tmpArray[1];
            
            NSUInteger loc = [src rangeOfString:@"\""].location;
            
            if (loc != NSNotFound) {
                
                src = [src substringToIndex:loc];
                
                [resultArray addObject:src];
                
            }
            
        }
        
    }
    
    return resultArray;
    
}


/**
 获取PHP接口的签名
 */
+(NSString *)getHomeWebSignature{
    
    NSString *randomStr = [CYUtils random:10];
    NSString *timestampStr = [CYUtils timestamp];
    NSString *combinationStr = [NSString stringWithFormat:@"random=%@&secret=123456&stamp=%@",randomStr,timestampStr];
    NSString *encryptionStr = [CYUtils stringToMD5:[CYUtils stringToSHA1:combinationStr]];
    NSString *signatureStr = [NSString stringWithFormat:@"signature=%@&stamp=%@&random=%@",encryptionStr,timestampStr,randomStr];
    return signatureStr;
}


/**
 获取设备型号然后手动转化为对应名称
 */
+ (NSString *)getDeviceName{
    
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (GSM+CDMA)";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5c (GSM)";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5c (GSM+CDMA)";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5s (GSM)";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5s (GSM+CDMA)";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceString isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    // 日行两款手机型号均为日本独占，可能使用索尼FeliCa支付方案而不是苹果支付
    if ([deviceString isEqualToString:@"iPhone9,1"])    return @"iPhone 7"; //! 国行、日版、港行
    if ([deviceString isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus"; //! 港行、国行
    if ([deviceString isEqualToString:@"iPhone9,3"])    return @"iPhone 7"; //! 美版、台版
    if ([deviceString isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus"; //! 美版、台版
    if ([deviceString isEqualToString:@"iPhone10,1"])   return @"iPhone 8"; //! 国行(A1863)、日行(A1906)
    if ([deviceString isEqualToString:@"iPhone10,4"])   return @"iPhone 8"; //! 美版(Global/A1905)
    if ([deviceString isEqualToString:@"iPhone10,2"])   return @"iPhone 8 Plus"; //! 国行(A1864)、日行(A1898)
    if ([deviceString isEqualToString:@"iPhone10,5"])   return @"iPhone 8 Plus"; //! 美版(Global/A1897)
    if ([deviceString isEqualToString:@"iPhone10,3"])   return @"iPhone X"; //! 国行(A1865)、日行(A1902)
    if ([deviceString isEqualToString:@"iPhone10,6"])   return @"iPhone X"; //! 美版(Global/A1901)
    if ([deviceString isEqualToString:@"iPhone11,8"])   return @"iPhone XR"; //! (A2108/A1984/A2105/A2106)
    if ([deviceString isEqualToString:@"iPhone11,2"])   return @"iPhone XS"; //! 美版(A2100/A2098/A2097/A1920)
    if ([deviceString isEqualToString:@"iPhone11,6"])   return @"iPhone XS Max"; //! 美版(A2104/A1921/A2101/A2102)
    if ([deviceString isEqualToString:@"iPhone12,1"])   return @"iPhone 11"; //! (A2221/A2223)
    if ([deviceString isEqualToString:@"iPhone12,3"])   return @"iPhone 11 Pro"; //! 美版(A2160/A2215/A2217)
    if ([deviceString isEqualToString:@"iPhone12,5"])   return @"iPhone 11 Pro Max"; //! 美版(A2161/A2220/A2218)
    
    
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    
    return deviceString;
}


/**
 比较两个版本号的大小
 
 @param v1 第一个版本号
 @param v2 第二个版本号
 @return 版本号相等,返回NO; v1小于v2,返回YES; 否则返回NO.
 */
+ (BOOL)compareVersion:(NSString *)v1 to:(NSString *)v2 {
    // 都为空，相等，返回0
    if (!v1 && !v2) {
        return NO;
    }
    
    // v1为空，v2不为空，返回1
    if (!v1 && v2) {
        return YES;
    }
    
    // v2为空，v1不为空，返回0
    if (v1 && !v2) {
        return NO;
    }
    
    // 获取版本号字段
    NSArray *v1Array = [v1 componentsSeparatedByString:@"."];
    NSArray *v2Array = [v2 componentsSeparatedByString:@"."];
    // 取字段最少的，进行循环比较
    NSInteger smallCount = (v1Array.count > v2Array.count) ? v2Array.count : v1Array.count;
    
    for (int i = 0; i < smallCount; i++) {
        NSInteger value1 = [[v1Array objectAtIndex:i] integerValue];
        NSInteger value2 = [[v2Array objectAtIndex:i] integerValue];
        if (value1 > value2) {
            // v1版本字段大于v2版本字段，返回1
            return NO;
        } else if (value1 < value2) {
            // v2版本字段大于v1版本字段，返回-1
            return YES;
        }
        
        // 版本相等，继续循环。
    }
    
    // 版本可比较字段相等，则字段多的版本高于字段少的版本。
    if (v1Array.count > v2Array.count) {
        return NO;
    } else if (v1Array.count < v2Array.count) {
        return YES;
    } else {
        return NO;
    }
    
    return NO;
}


/// 判断手机型号是否为6s以后机型
+ (BOOL)iphoneType{
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    //支持设备为6s及以上
    if (![platform containsString:@"iPhone"]) {
        return NO;
    }
    NSRange range = [platform rangeOfString:@","];
    platform = [platform substringToIndex:range.location];
    platform = [platform substringFromIndex:6];
    NSInteger iphoneV = [platform integerValue];
    //异常处理，防止以后出现iPhone后面是字符串的情况
    if (iphoneV == 0) {
        iphoneV = 8;
    }
    
    NSLog(@"%ld",(long)iphoneV);
    return  iphoneV > 7 ? YES : NO;
    
}


/// 两个颜色平滑渐变---根据系数返回对应颜色
/// @param beginColor 开始颜色
/// @param endColor 结束颜色
/// @param scal 系数
+(UIColor *)getColorWithBeginColor:(UIColor *)beginColor toEndColor:(UIColor *)endColor withScal:(CGFloat)scal{
    
    if (scal >= 1) {
        return endColor;
    }
    
    NSArray * marginArr = [self transColorBeginColor:beginColor andEndColor:endColor];
    
    UIColor * color = [self getColorWithColor:beginColor andCoe:scal andMarginArray:marginArr];
    
    return color;
}


/// 获取颜色的r、g、b的值
+ (NSArray *)getRGBDictionaryByColor:(UIColor *)originColor
{
  CGFloat r=0,g=0,b=0,a=0;
  if ([self respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
    [originColor getRed:&r green:&g blue:&b alpha:&a];
  }
  else {
    const CGFloat *components = CGColorGetComponents(originColor.CGColor);
    r = components[0];
    g = components[1];
    b = components[2];
    a = components[3];
  }
  return @[@(r),@(g),@(b)];
}


/// 计算两个颜色r、g、b的差值
/// @param beginColor 开始颜色
/// @param endColor 结束颜色
+ (NSArray *)transColorBeginColor:(UIColor *)beginColor andEndColor:(UIColor *)endColor {
  NSArray<NSNumber *> *beginColorArr = [self getRGBDictionaryByColor:beginColor];
  NSArray<NSNumber *> *endColorArr = [self getRGBDictionaryByColor:endColor];
//  NSArray<NSNumber *> *endColorArr = @[@(1.0),@(1.0),@(1.0)];
  return @[@([endColorArr[0] doubleValue] - [beginColorArr[0] doubleValue]),@([endColorArr[1] doubleValue] - [beginColorArr[1] doubleValue]),@([endColorArr[2] doubleValue] - [beginColorArr[2] doubleValue])];
}


/// 获取对应比例的过渡颜色
/// @param beginColor 开始颜色
/// @param coe 系数
/// @param marginArray 差值数组
+ (UIColor *)getColorWithColor:(UIColor *)beginColor andCoe:(double)coe andMarginArray:(NSArray<NSNumber *> *)marginArray {
  NSArray *beginColorArr = [self getRGBDictionaryByColor:beginColor];
  double red = [beginColorArr[0] doubleValue] + coe * [marginArray[0] doubleValue];
  double green = [beginColorArr[1] doubleValue]+ coe * [marginArray[1] doubleValue];
  double blue = [beginColorArr[2] doubleValue] + coe * [marginArray[2] doubleValue];
    return [UIColor colorWithRed:red green:green blue:blue alpha:1];
}


/**
 基础计算 截取指定小数位数 时间耗时较少
 */
+ (NSString *)getRoundFloat:(double)floatNumber{
    
    NSString *tempString = [NSString stringWithFormat:@"%f",floatNumber];
    //计算截取的长度
    NSUInteger endLength = tempString.length;
    //判断字符串是否包含 .
    if ([tempString containsString:@"."]) {
        //取得 . 的位置
        NSRange pointRange = [tempString rangeOfString:@"."];
        //判断 . 后面有几位
        NSUInteger f = tempString.length - 1 - pointRange.location;
        //如果大于2位就截取字符串保留两位,如果小于两位,直接截取
        if (f > 2) {
            endLength = pointRange.location + 3;
        }
    }
    
    NSString *returnString = [tempString substringToIndex:endLength];
     CYLog(@"%@,%f",returnString,floatNumber);
    return returnString;
}


#pragma mark - 获取设备当前网络IP地址
+ (NSString *)getIPAddress
{
    
    NSArray *searchArray =
    @[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] ;

    NSDictionary *addresses = [self getIPAddresses];
    NSLog(@"addresses: %@", addresses);

    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
     {
         address = addresses[key];
         //筛选出IP地址格式
         if([self isValidatIP:address]) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}

+ (BOOL)isValidatIP:(NSString *)ipAddress {
    if (ipAddress.length == 0) {
        return NO;
    }
    NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];

    if (regex != nil) {
        NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];

        if (firstMatch) {
            NSRange resultRange = [firstMatch rangeAtIndex:0];
            NSString *result=[ipAddress substringWithRange:resultRange];
            //输出结果
            NSLog(@"%@",result);
            return YES;
        }
    }
    return NO;
}

+ (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];

    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}


/**
 获取手机运营商
 */
+(NSString *)getSIMOperator{

    CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = networkInfo.subscriberCellularProvider;
    NSString *carrier_country_code = carrier.isoCountryCode;

    if (carrier_country_code == nil) {
        carrier_country_code = @"";
    }
    //国家编号
    NSString *CountryCode = carrier.mobileCountryCode;

    if (CountryCode == nil) {
        CountryCode = @"";
    }
    //网络供应商编码
    NSString *NetworkCode = carrier.mobileNetworkCode;

    if (NetworkCode == nil) {
        NetworkCode = @"";
    }

    NSString *mobile_country_code = [NSString stringWithFormat:@"%@%@",CountryCode,NetworkCode];

    if (mobile_country_code == nil) {
        mobile_country_code = @"";
    }

    NSString *carrier_name = nil;    //网络运营商的名字
    NSString *code = [carrier mobileNetworkCode];

    if ([code isEqualToString:@"00"] || [code isEqualToString:@"02"] || [code isEqualToString:@"07"]) {
        // ret = @"移动"
        carrier_name = @"0";
      }
    
    if ([code isEqualToString:@"01"] || [code isEqualToString:@"06"]|| [code isEqualToString:@"09"]) {
        // ret = @"联通";
        carrier_name =  @"1";
    }
  
    if ([code isEqualToString:@"03"] || [code isEqualToString:@"05"]|| [code isEqualToString:@"11"]) {
        // ret = @"电信";
        carrier_name =  @"2";
    }
    
    if (code == nil) {
        carrier_name = @"-1";
    }

//    carrier_name = [NSString stringWithFormat:@"%@-%@",carrier_name,[carrier.carrierName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    CYLog(@"运营商:%@", carrier_name);
    return carrier_name;
}


/**
 获取不需要任何提示的接口名称,如果该接口调用时需要对用户无感,不需要任何提示,那么要把接口添加到这个数组里面
 返回值为YES就是需要弹窗的
 */
+ (BOOL )getNeedTipApis:(NSString *)urlStr{
    NSArray *apis = @[
        @"/ftms-iov-app-user/user/sendFanControl",
        @"/ftms-iov-app-user/user/initApp"
    ];
    BOOL isNeedTip = YES;
    for (NSString *url in apis) {
        if ([urlStr containsString:url]) {
            isNeedTip = NO;
            break;
        }
    }
    return isNeedTip;
}


/// 将服务器返回Jason中null或者<null>处理为@""
/// @param obj 服务器返回Jason
+ (id) processDictionaryIsNSNull:(id)obj{
    const NSString *blank = @"";
  
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *dt = [(NSMutableDictionary*)obj mutableCopy];
        for(NSString *key in [dt allKeys]) {
            id object = [dt objectForKey:key];
            if([object isKindOfClass:[NSNull class]]) {
                [dt setObject:blank
                             forKey:key];
            }
            else if ([object isKindOfClass:[NSString class]]){
                NSString *strobj = (NSString*)object;
                if ([strobj isEqualToString:@"<null>"]) {
                    [dt setObject:blank
                           forKey:key];
                }
            }
            else if ([object isKindOfClass:[NSArray class]]){
                NSArray *da = (NSArray*)object;
                da = [self processDictionaryIsNSNull:da];
                [dt setObject:da
                       forKey:key];
            }
            else if ([object isKindOfClass:[NSDictionary class]]){
                NSDictionary *ddc = (NSDictionary*)object;
                ddc = [self processDictionaryIsNSNull:object];
                [dt setObject:ddc forKey:key];
            }
        }
        return [dt copy];
    }
    else if ([obj isKindOfClass:[NSArray class]]){
        NSMutableArray *da = [(NSMutableArray*)obj mutableCopy];
        for (int i=0; i<[da count]; i++) {
            NSDictionary *dc = [obj objectAtIndex:i];
            dc = [self processDictionaryIsNSNull:dc];
            [da replaceObjectAtIndex:i withObject:dc];
        }
        return [da copy];
    }
    else{
        return obj;
    }
}


/// 读取本地json数据
/// @param fileName 文件名称
+(id)getLocationData:(NSString *)fileName{
    
    NSData * data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:@"json"]];
    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    
    return result;
    
}


/// 获取N个月前的年和月
/// @param number N个月前
+(NSDictionary *)getNumberYearAndMonth:(NSInteger)number{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-M"];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
//    [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期，month day 类推
    [lastMonthComps setMonth:-number];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    NSString *dateStr = [formatter stringFromDate:newdate];
    
    NSArray * dateArr = [dateStr componentsSeparatedByString:@"-"];
    NSMutableDictionary * dateDic = [NSMutableDictionary dictionaryWithCapacity:2];
    [dateDic setObject:dateArr.firstObject forKey:@"year"];
    [dateDic setObject:dateArr.lastObject forKey:@"month"];
    return dateDic;
}
/// 根据字符串获取对应参数
+ (NSString *)filterUsingPredicateArray:(NSArray *)filterArray andContainer:(NSString *)containStr {
    NSArray *tmpArray =  [filterArray filteredArrayUsingPredicate: [NSPredicate predicateWithFormat:@"SELF CONTAINS %@", containStr]];
    
    NSString * value = @"";
    if (tmpArray) {
        value = tmpArray.firstObject;
        value = [value substringFromIndex:containStr.length];
    }
    return  value;
}
@end
